package demo.db.apollo;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.springframework.beans.factory.annotation.Value;

/**
 * https://github.com/apolloconfig/apollo/wiki/Apollo%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83%E8%AE%BE%E8%AE%A1
 */
public class TestApolloAnnotationBean {

    @ApolloConfig
    private Config config; // inject config for namespace application

    @ApolloConfig("application")
    private Config anotherConfig; // inject config for namespace application

    @ApolloConfig("FX.apollo")
    private Config yetAnotherConfig; // inject config for namespace FX.apollo

    @Value("${batch:100}")
    private int batch;

    // config change listener for namespace application

    @ApolloConfigChangeListener
    private void someOnChange(ConfigChangeEvent changeEvent) {
        // update injected value of batch if it is changed in Apollo
        if (changeEvent.isChanged("batch")) {
            batch = config.getIntProperty("batch", 100);
        }
    }

    // config change listener for namespace application

    @ApolloConfigChangeListener("application")
    private void anotherOnChange(ConfigChangeEvent changeEvent) {
        // do something
    }

    // config change listener for namespaces application and FX.apollo

    @ApolloConfigChangeListener({ "application", "FX.apollo" })
    private void yetAnotherOnChange(ConfigChangeEvent changeEvent) {

        // do something

    }

    // example of getting config from Apollo directly
    // this will always return the latest value of timeout
    public int getTimeout() {

        return config.getIntProperty("timeout", 200);

    }

    // example of getting config from injected value
    // the program needs to update the injected value when batch is changed in Apollo using @ApolloConfigChangeListener
    // shown above
    public int getBatch() {
        return this.batch;
    }
}
